package com.wen.controller.utils.http;

import lombok.Data;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

/**
 * Http Client 工具类
 * <p>
 *
 * @author devin <devinlive@163.com>
 * @version 1.0
 * @since 2023/09/06 13:39
 */
public class HttpUtil {

    public void exampleWebClientGet() {
        WebClient webClient = WebClient.create();

        String uri = "https://api.example.com/endpoint";

        // 设置查询参数
        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("param1", "value1");
        queryParams.add("param2", "value2");

        // 构建完整的 URL 包括查询参数
        String requestUrl = UriComponentsBuilder.fromUriString(uri)
                .queryParams(queryParams)
                .toUriString();


        // 发送 GET 请求
        Mono<String> responseMono = webClient.get()
                .uri(requestUrl)
                .retrieve()
                .bodyToMono(String.class);

        responseMono.subscribe(responseBody -> {
            System.out.println("Response Body: " + responseBody);
        });
    }

    public void exampleWebClientPost() {
        WebClient webClient = WebClient.create();

        String url = "https://api.example.com/endpoint";

        // 设置请求体参数
        ReqsBody body = new ReqsBody();
        body.setParam1("value1");
        body.setParam2("value2");

        // 发送 POST 请求并设置请求体
        Mono<String> responseMono = webClient.post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(body))
//                .bodyValue(body) // String body = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
                .retrieve()
                .bodyToMono(String.class);

        responseMono.subscribe(responseBody -> {
            System.out.println("Response Body: " + responseBody);
        });
    }
}


@Data
class ReqsBody {
    private String param1;
    private String param2;
}
